# config_dialog.py
from PySide2.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QFormLayout,
                               QLabel, QLineEdit, QPushButton, QDialogButtonBox)
from PySide2.QtCore import Qt
import os
from servers_config_manager import ConfigManager


class ServersConfigDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("路段服务器文件配置")
        self.setMinimumWidth(640)

        # 加载配置
        self.config_manager = ConfigManager()

        # 创建表单布局
        layout = QFormLayout(self)


        # 堡垒机信息文件路径
        self.servers_path_edit = QLineEdit()
        self.servers_path_edit.setText(self.config_manager.get_servers_path())
        servers_browse_btn = QPushButton("浏览...")
        servers_browse_btn.clicked.connect(self.browse_servers_xlsx)

        servers_layout = QHBoxLayout()
        servers_layout.addWidget(self.servers_path_edit)
        servers_layout.addWidget(servers_browse_btn)

        # 添加路段服务器表格列名配置
        self.servers_columns_edit = QLineEdit()
        self.servers_columns_edit.setText(", ".join(self.config_manager.get_servers_columns()))
        self.servers_columns_edit.setPlaceholderText("请输入路段服务器表格列名，用逗号分隔")

        # 添加到表单
        layout.addRow("路段服务器文件路径:", servers_layout)
        layout.addRow("路段服务器表格列名:", self.servers_columns_edit)

        # 对话框按钮
        buttons = QDialogButtonBox()
        save_button = QPushButton("保存")
        cancel_button = QPushButton("取消")
        buttons.addButton(save_button, QDialogButtonBox.AcceptRole)
        buttons.addButton(cancel_button, QDialogButtonBox.RejectRole)
        save_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        layout.addRow(buttons)


    def browse_servers_xlsx(self):
        from PySide2.QtWidgets import QFileDialog
        file_filter = "堡垒机信息 (*.xlsx);;所有文件 (*.*)" if os.name == 'nt' else "所有文件 (*)"
        path, _ = QFileDialog.getOpenFileName(
            self, "选择堡垒机信息文件", self.servers_path_edit.text(), file_filter
        )
        if path:
            self.servers_path_edit.setText(path.replace("/", os.sep))

    def accept(self):
        # 保存设置
        self.config_manager.set_servers_path(self.servers_path_edit.text())
        # 保存表格列名配置
        self.config_manager.set_servers_columns([col.strip() for col in self.servers_columns_edit.text().split(',') if col.strip()])
        super().accept()

    def get_config(self):
        return {
            "login_path": self.servers_path_edit.text()
        }



